package com.sgj.gulimall.order.controller;

import com.alibaba.fastjson.JSONObject;
import com.sgj.gulimall.order.entity.OrderEntity;
import com.sgj.gulimall.order.entity.OrderReturnReasonEntity;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.UUID;

/**
 * @Author: Guoji Shen
 * @Date: 2021/9/17 15:07
 */
@Slf4j
@RestController
public class RabbitController {

    // 交换机名称
    public static final String EXCHANGENAME = "hello-java-exchange";
    // 队列名称
    public static final String QUEUENAME = "hello-java-queue";
    // 路由
    public static final String ROUTE = "hello.java";

    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 发送消息到队列
     * @param num
     * @return
     */
    @GetMapping("/sendMessage")
    public String sendMessage(@RequestParam(value = "num", defaultValue = "10") Integer num) {
        // 要发送的消息
        for (int i = 0; i < num; i++) {
            if (i % 2 == 0) {
                OrderReturnReasonEntity entity = OrderReturnReasonEntity.builder()
                        .id(1L)
                        .createTime(new Date())
                        .name("哈哈哈哈哈哈")
                        .build();

                rabbitTemplate.convertAndSend(EXCHANGENAME, ROUTE, entity, new CorrelationData(UUID.randomUUID().toString()));
                // log.info("消息1发送成功:{}", JSONObject.toJSONString(entity));
            } else {
                OrderEntity entity = OrderEntity.builder()
                        .id(2L)
                        .orderSn(UUID.randomUUID().toString())
                        .receiverName("花花互动哈速度哈苏")
                        .build();

                rabbitTemplate.convertAndSend(EXCHANGENAME, ROUTE + "22", entity, new CorrelationData(UUID.randomUUID().toString()));
                // log.info("消息2发送成功:{}", JSONObject.toJSONString(entity));
            }
        }
        return "消息已发送成功";
    }
}